package com.yourbatis.syntax;

public class BinaryExpression implements Expression {
    private ASTNode left;
    private String operator;
    private ASTNode right;

    public BinaryExpression(ASTNode left, String operator, ASTNode right) {
        this.left = left;
        this.operator = operator;
        this.right = right;
    }

    @Override
    public Object eval() {
        Object leftValue = left.eval();
        Object rightValue = right.eval();
        switch (operator) {
            case "+":
                return toCalc(leftValue, rightValue);
            case "-":
                return (Integer)leftValue - (Integer)rightValue;
            case "*":
                return (Integer)leftValue * (Integer)rightValue;
            case "/":
                return (Integer)leftValue / (Integer)rightValue;
            case "==":
                return equal(leftValue, rightValue);
            case "!=":
                return !equal(leftValue, rightValue);
            case ">":
                return (Integer)leftValue > (Integer)rightValue;
            case ">=":
                return (Integer)leftValue >= (Integer)rightValue;
            case "<":
                return (Integer)leftValue < (Integer)rightValue;
            case "<=":
                return (Integer)leftValue <= (Integer)rightValue;
        }
        return null;
    }

    private boolean equal(Object leftValue, Object rightValue) {
        if (leftValue instanceof String && rightValue instanceof String){
            return leftValue.equals(rightValue);
        }
        if(leftValue instanceof Integer && rightValue instanceof Integer){
            return leftValue.equals(rightValue);
        }


        return leftValue == rightValue;
    }

    public Object toCalc(Object leftValue, Object rightValue) {
        if(leftValue instanceof String){
            if(rightValue instanceof String){
                return leftValue + (String)rightValue;
            }else{
                return leftValue + rightValue.toString();
            }
        }else{
            if(rightValue instanceof String){
                return leftValue.toString() + rightValue;
            }else{
                return (Integer)leftValue + (Integer)rightValue;
            }
        }
    }
}
